'use strict';
var app = angular.module('app');
app.controller('authCreateController', ['$scope', '$rootScope', '$state', '$timeout', 'toaster', '$modal',
    function($scope, $rootScope, $state, $timeout, toaster, $modal) {
        $scope.record = {
            authType: 0,
            id: $state.params.id,
            status: 1,
            icCardUIDs: []
        };
        $scope.record.idCardUID = '';
        $scope.record.liveCardUID = '';
        $scope.record.icCardUIDs = [];
        $scope.cardUUIDStatus = false; //身份证UID状态
        $scope.liveCardUUIDStatus = false; //居住证UID
        $scope.icCardUUIDStatus = false; //IC卡UID
        var timer1, timer2, timer3, prevCard;

        //设置编辑时地址、人员信息框不可修改
        if ($scope.record.id != null) {
            $scope.isreadonly = true;
        } else {
            $scope.isreadonly = false;
        }
        if ($state.includes('**.authm.cardAuth.update')) {
            $scope.loading = true;
            $scope.reset = false; //修改不允许重置
            $scope.title = "修改授权";
            var id = $state.params.id;
            activate(id);
            validate();
        } else if ($state.includes('**.authm.cardAuth.create')) {
            $scope.title = "新增授权";
            $scope.reset = true; //新增时可以重置
            validate();
            $scope.record.appAvalible = '1';

        }

        //重置表单
        $scope.resetFrom = function() {
            $scope.record = {
                authType: 0,
                id: $state.params.id,
                status: 1,
                icCardUIDs: []
            };
        }

        // 初始化页面
        function activate(id) {
            $scope.loading = true;
            $.ajax({
                type: 'PUT',
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                url: '/dac/authm/selectByAuthorId',
                data: angular.toJson({
                    'id': id
                })
            }).then(function(result) {
                $scope.loading = false;
                if (result.httpCode == 200) {
                    var item = result.data;
                    $scope.pname = item.personName;
                    $scope.record.personId = item.personId;
                    $scope.bname = item.locationName;
                    $scope.record.deviceId = item.deviceId;
                    $scope.record.authNo = item.authNo;
                    $scope.record.authType = item.authType;
                    $scope.record.status = item.status;
                    $scope.record.endTime = item.endTime;
                    $scope.record.buildingAddress = item.locationName;
                    $scope.record.idCardUID = item.idCardUID;
                    $scope.record.liveCardUID = item.liveCardUID;
                    $scope.record.icCardUIDs = item.icCardUIDs; //数组
                    $scope.postBack = item.icCardUIDs; //绑定给迭代对象
                    //app授权判断
                    if (item.authorType == "1") {
                        $scope.record.appAvalible = '1';
                    } else {
                        $scope.record.appAvalible = '0';
                    }
                } else {
                    $scope.msg = result.msg;
                }
                $scope.$apply();
            });
        }

        //读卡器状态
        function clearCardStatus(status) {
            if (!!window.ActiveXObject || "ActiveXObject" in window) {} else {
                toaster.pop('error', '', '该功能只支持IE浏览器，请使用IE浏览器！');
                return;
            }
            var ports = webSerial.getComPorts(); //获取到端口号
            var coms = ports;
            if (!coms) {
                toaster.pop('error', '', "设备异常，请检查您的读卡设备！");
                return;
            }
            var baudRate = '115200';
            var result = webSerial.connect(coms, baudRate);
            if (result == "true" || result == true) {
                clearInterval(timer1)
                clearInterval(timer2)
                clearInterval(timer3)
                $scope.cardUUIDStatus = false;
                $scope.liveCardUUIDStatus = false;
                $scope.icCardUUIDStatus = false;
                $scope[status] = true;
            } else {
                toaster.pop('error', '', "设备异常，请检查您的读卡设备！");
            }
        }

        //获取卡号
        function cardHandle(data) {
            var code = data.split(" ");
            var targetStr = "";
            for (var i = 0; i < code.length; i++) {
                var tmp = parseInt(code[i], 16);
                targetStr += String.fromCharCode(tmp);
            }

            var cardId = targetStr.replace(/^0+/, "") //把设备读取卡号前面补的‘0’全部去掉
            cardId = cardId.replace(/(^\s*)|(\s*$)/g, ""); //把数据后面的回车空格去掉
            prevCard = cardId;
            return cardId;
        }

        //表单的提交
        $scope.submit = function() {
            if ($scope.record.icCardUIDs.length > 0 || $scope.record.idCardUID !== undefined || $scope.record.liveCardUID !== undefined || $scope.record.appAvalible == '1') {
                var m = $scope.record;
                console.log(m)
                if ($scope.record.id != null) { //id非空代表着是修改
                    if (m) {
                        $scope.isDisabled = true; //提交disabled
                        $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            // url : 'dac/authm/cardAuth/update',
                            url: 'dac/authm/cardAuth/nupdate',
                            data: angular.toJson($scope.record)
                        }).then(function(result) {
                            if (result.httpCode == 200) { //成功
                                toaster.clear('*');
                                toaster.pop('success', '', "保存成功");
                                $timeout(function() {
                                    $state.go('main.authm.cardAuth.list');
                                }, 3000);
                            } else {
                                toaster.clear('*');
                                toaster.pop('error', '', result.msg);
                                $scope.isDisabled = false;
                            }
                        });
                    }

                } else { //id为空代表着是新增
                    if (m) {
                        $scope.isDisabled = true; //提交disabled
                        $.ajax({
                            type: 'POST',
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            // url : 'dac/authm/cardAuth/insert',
                            url: 'dac/authm/cardAuth/ninsert',
                            data: angular.toJson($scope.record)
                        }).then(function(result) {
                            if (result.httpCode == 200) { //成功
                                toaster.clear('*');
                                toaster.pop('success', '', "保存成功");
                                $timeout(function() {
                                    $state.go('main.authm.cardAuth.list');
                                }, 2000);
                            } else {
                                toaster.clear('*');
                                toaster.pop('error', '', result.msg);
                                $scope.isDisabled = false;
                            }
                        });
                    }

                }
            } else {
                alert('身份证、居住证、IC卡、APP开门四者至少填一项');
                return //如果三者都不填的话就不执行下面的代码，不提交！
            }

        }
        //表单验证
        function validate() {
            jQuery('form').validate({
                rules: {
                    pname: {
                        required: true
                    },
                    bname: {
                        required: true
                    },
                    authNo: {
                        required: true
                    },
                    authType: {
                        required: true
                    },
                    endTime: {
                        required: true
                    }
                },
                messages: {
                    pname: {
                        required: '请填写姓名'
                    },
                    bname: {
                        required: '请填写房屋地址'
                    },
                    authNo: {
                        required: '请填写门禁卡号'
                    },
                    authType: {
                        required: '请选择卡类型'
                    },
                    endTime: {
                        required: '请选择结束时间'
                    }
                },
                submitHandler: function() {
                    $scope.submit();
                }
            });
        }
        //日期控件
        $scope.dateOptions = {
            startingDay: 1,
            class: 'datepicker'
        };
        //日期控件
        $scope.format = "yyyy-MM-dd";
        $scope.openDatepicker = function($event, i) {
            $event.preventDefault();
            $event.stopPropagation();
            if (i == 1) {
                $scope.beginTime = true;
            } else if (i == 2) {
                $scope.endTime = true;
            }
        }

        //现住地址模态框
        $scope.openNowAddress = function() {
            var modalInstance = $modal.open({
                templateUrl: 'NowAddress.html', //script标签中定义的id
                controller: 'NowAddressModalCtrl', //modal对应的Controller
                size: 'lg',
                resolve: {
                    items: function() {
                        return ''
                    }
                }
            });

            modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

            });
            modalInstance.result.then(function(result) {
                if (result) {
                    $scope.record.deviceId = result.deviceId;
                    $scope.record.buildingAddress = result.buildingAddress;
                    $scope.record.buildingId = result.buildingId;
                } else {
                    toaster.clear('*');
                    toaster.pop('error', '', '没有数据返回！');
                }
            }, function(reason) {
                console.log(reason);
            });

        };

        //姓名模态框
        $scope.openPerson = function(buildingId) {

            $scope.items = buildingId;
            var modalInstance = $modal.open({
                templateUrl: 'personList.html', //script标签中定义的id
                controller: 'personModalCtrl', //modal对应的Controller
                size: 'lg',
                resolve: {
                    items: function() {
                        return $scope.items;
                    }
                }
            });

            modalInstance.opened.then(function() { // 模态窗口打开之后执行的函数

            });
            modalInstance.result.then(function(result) {
                $scope.pname = result[0];
                $scope.record['personId'] = result[1];
                $scope.record.authNo = result[2];
            }, function(reason) {
                console.log(reason);
            });
        };

        //身份证
        $scope.readIdCard = function() {
            // var ports = webSerial.getComPorts();
            // var coms = ports;
            // var baudRate = '115200';
            // var result = webSerial.connect(coms, baudRate);
            clearCardStatus('cardUUIDStatus');
            var webSerial1 = document.getElementById("webSerial");
            var s = 0;
            timer1 = setInterval(function() {
                s += 2;
                var data1 = webSerial1.Receive();
                if (data1 != null) {
                    var card_id = cardHandle(data1);
                    if ($scope.record.liveCardUID.indexOf(card_id) == -1 && $scope.record.icCardUIDs.toString().indexOf(card_id) == -1) {
                        $scope.cardUUIDStatus = false;
                        $scope.record.idCardUID = card_id;
                        webSerial.close();
                        clearInterval(timer1);
                        $scope.$apply();
                    }
                }
                if (s >= 10) {
                    s = 0;
                    $scope.cardUUIDStatus = false;
                    $scope.$digest();
                    clearInterval(timer1);
                    toaster.pop('error', '', "读取超时或请确认是否重复读卡！");
                }

            }, 2000);
        }

        $scope.readLiveCard = function() {
            // var ports = webSerial.getComPorts();
            // var coms = ports;
            // var baudRate = '115200';
            // var result = webSerial.connect(coms, baudRate);
            clearCardStatus('liveCardUUIDStatus');
            var webSerial1 = document.getElementById("webSerial");
            var s = 0;
            timer2 = setInterval(function() {
                s += 2;
                var data1 = webSerial1.Receive();
                if (data1 != null) {
                    var card_id = cardHandle(data1);
                    if ($scope.record.idCardUID.indexOf(card_id) == -1 && $scope.record.icCardUIDs.toString().indexOf(card_id) == -1) {
                        $scope.liveCardUUIDStatus = false;
                        $scope.record.liveCardUID = card_id;
                        prevCard = card_id;
                        webSerial.close();
                        clearInterval(timer2);
                        $scope.$apply();
                    }
                }
                if (s >= 10) {
                    s = 0;
                    $scope.liveCardUUIDStatus = false;
                    $scope.$digest();
                    clearInterval(timer2);
                    toaster.pop('error', '', "读取超时或请确认是否重复读卡！");
                }

            }, 2000);
        }

        $scope.readIcCard = function() {
            // var ports = webSerial.getComPorts(); //获取到端口号
            // var coms = ports;
            // var baudRate = '115200';
            // var result = webSerial.connect(coms, baudRate);
            // console.log(result);
            clearCardStatus('icCardUUIDStatus');
            var webSerial1 = document.getElementById("webSerial"); //页面上的特定结构
            var s = 0;
            timer3 = setInterval(function() { //设置定时器，检测刷卡动作
                s += 2;
                var data1 = webSerial1.Receive();
                if (data1) { //刷卡有数据时，对数据处理，关闭定时器与控件
                    var card_id = cardHandle(data1);
                    if ($scope.record.liveCardUID.indexOf(card_id) == -1 && $scope.record.idCardUID.indexOf(card_id) == -1) {
                        $scope.icCardUUIDStatus = false;
                        $scope.record.icCardUIDs.push(card_id);
                        prevCard = card_id;
                        webSerial.close();
                        clearInterval(timer3);
                        $scope.$apply();
                    }
                }
                if (s >= 10) {
                    s = 0;
                    $scope.icCardUUIDStatus = false;
                    $scope.$digest()
                    clearInterval(timer3);
                    toaster.pop('error', '', "读取超时或请确认是否重复读卡！");
                }


            }, 2000);

        }
        //删除已录入的卡号
        $scope.del = function(idx) {
            $scope.record.icCardUIDs.splice(idx, 1);
            console.log($scope.record.icCardUIDs);
        };

        //选取时间
        $scope.chooceTime = function(Months) {
            console.log(Months);
            var endTime = '';
            if (Months && Months != undefined) {
                var date = new Date();
                date.setMonth(date.getMonth() + Months);
                var year = date.getFullYear();
                var Month = date.getMonth() + 1;
                var day = date.getDate();
                if (Month > 12) {
                    year = year + 1;
                    Month = Month - 12;
                }
                switch (Month) {
                    case 1:
                    case 3:
                    case 5:
                    case 7:
                    case 8:
                    case 10:
                    case 12:
                        console.log(Month)
                        break;
                    case 4:
                    case 6:
                    case 9:
                    case 11:
                        if (day > 30) {
                            day = 30;
                        }
                        break;
                    case 2:
                        if (day > 28) {
                            day = 29;
                        }
                        break;
                    default:
                        console.log(Month);
                }
                if (Month < 10) {
                    Month = '0' + Month
                }
                if (day < 10) {
                    day = '0' + day
                }
                endTime = year + '-' + Month + '-' + day;
                console.log(endTime);
                $scope.record.endTime = endTime;
            } else {
                $scope.record.endTime = '2099-12-31';
            }
        };


    }
]);


//现住地址模态框控制器
app.controller('NowAddressModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items) {
    if (items) {
        $scope.url = '/dac/authm/build/bypersonlist'
    } else {
        $scope.url = '/dac/authm/build/list'
    }
    $scope.param = {};
    $scope.search = function() {
        $scope.loading = true;
        if ($scope.pageFlag != 1) { //未点击翻页
            $scope.param.pageNum = 1; //将页码设置为1，即跳转回第一页
        } else { //点击翻页
            $scope.pageFlag = 2; //将开关值设置为2
        }
        $scope.param.cityId = $('#city').find("option:selected").data('code'); //获取value的值
        $scope.param.areaId = $('#areaId').find("option:selected").data('code'); //获取value的值
        $scope.param.streetId = $('#streetId').find("option:selected").data('code'); //获取value的值
        $scope.param.roadId = $('#roadId').find("option:selected").data('code'); //获取value的值
        $scope.param.communityId = $('#quarters').find("option:selected").data('code'); //获取value的值
        $scope.param.buildingNo = $('#buildingNo').val();
        $scope.param.deviceCode = $('#deviceCode').val();
        $scope.param.deviceName = $('#deviceName').val();
        $scope.param.personId = $('#personId').val();
        $scope.param.buildName = $('#buildName').val();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: $scope.url,
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                console.log(result)
                $scope.pageInfo = result;
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }
    $scope.search();

    //7级地址下拉数据
    //市
    $scope.getaddress = function() {
        $scope.param = {
            parentCode: 440000 //广东省
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.city = result.data;
            console.log(result);
        })
    }
    $scope.getaddress();
    //区
    $scope.getarea = function() {
        var parentCode = $('#city').find("option:selected").data('code'); //获取value的值
        console.log(parentCode);
        $scope.param = {
            parentCode: parentCode //广州市区级
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.area = result.data;
            console.log(result);
        })
    }
    //乡镇/街道
    $scope.getStree = function() {
        var parentCode = $('#area').find("option:selected").data('code'); //获取value的值
        console.log(parentCode);
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.stree = result.data;
            console.log(result);
        })
    }
    //路
    $scope.getRoad = function() {
        var parentCode = $('#street').find("option:selected").data('code'); //获取value的值;
        console.log(parentCode)
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.roud = result.data;
            console.log(result);
        })
    }
    //小区
    $scope.getQuarters = function() {
        var parentCode = $('#road').find("option:selected").data('code'); //获取value的值;
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.quarters = result.data;
            console.log(result);
        })
    }
    //房号
    $scope.getHouseNo = function() {
        var parentCode = $('#quarters').find("option:selected").data('code'); //获取value的值;
        $scope.param = {
            parentCode: parentCode
        };
        $.ajax({
            type: 'PUT',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dic/queryDicListByParentId',
            data: angular.toJson($scope.param)
        }).then(function(result) {
            $scope.houseNo = result.data;
            console.log(result);
        })
    }
    //选择按钮操作
    $scope.selectBuilding = function(buildingId, buildingAddress, deviceId) {
        $scope.buildingId = {
            buildingId: buildingId,
            buildingAddress: buildingAddress,
            deviceId: deviceId
        }
        $modalInstance.close($scope.buildingId);
    };
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };
    // 翻页
    $scope.pagination = function(page) {
        $scope.param.pageNum = page;
        $scope.pageFlag = 1; //将开关值设置为1
        $scope.search();
    };

});

//姓名模态框控制器
app.controller('personModalCtrl', function($scope, $rootScope, $modal, $modalInstance, items) {

    $scope.paramP = {
        buildingId: items //buildingId
    };

    $scope.searchP = function() {
        $scope.loading = true;
        if ($scope.pageFlag != 1) { //未点击翻页
            $scope.paramP.pageNum = 1; //将页码设置为1，即跳转回第一页
        } else { //点击翻页
            $scope.pageFlag = 2; //将开关值设置为2
        }
        $.ajax({
            type: 'POST',
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            url: '/dac/authm/person/list',
            data: angular.toJson($scope.paramP)
        }).then(function(result) {
            $scope.loading = false;
            if (result.httpCode == 200) {
                console.log(result.data)
                $scope.pageInfo = result;
            } else {
                $scope.msg = result.msg;
            }
            $scope.$apply();
        });
    }

    $scope.searchP();

    $scope.selectPerson = function(pid, pname, IDCardNo) {
        $scope.params = [];
        $scope.params[0] = pname;
        $scope.params[1] = pid;
        $scope.params[2] = IDCardNo;
        $modalInstance.close($scope.params);
    };
    $scope.cancel = function() {
        $modalInstance.dismiss('cancel');
    };

    // 翻页
    $scope.pagination = function(page) {
        $scope.paramP.pageNum = page;
        $scope.pageFlag = 1; //将开关值设置为1
        $scope.searchP();
    };
});